﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;

namespace ExcelBlockLib
{
    public static class MaterialFieldLoader
    {
        public static Dictionary<string, List<string>> LoadFieldMapFromExcel(string excelPath)
        {
            var map = new Dictionary<string, List<string>>();

            if (!File.Exists(excelPath))
                throw new FileNotFoundException("找不到字段定义文件: " + excelPath);

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using (var package = new ExcelPackage(new FileInfo(excelPath)))
            {
                var sheet = package.Workbook.Worksheets[0];
                int startRow = 3;

                string currentMaterial = null;
                var currentFields = new List<string>();

                for (int row = startRow; row <= sheet.Dimension.End.Row; row++)
                {
                    var nameCell = sheet.Cells[row, 1]; // A列：材质名称（含编号）
                    var fieldCell = sheet.Cells[row, 2]; // B列：字段名

                    bool isNewMaterial = !string.IsNullOrWhiteSpace(nameCell.Text);

                    if (isNewMaterial)
                    {
                        if (currentMaterial != null && currentFields.Count > 0)
                            map[currentMaterial] = new List<string>(currentFields);

                        currentMaterial = nameCell.Text.Trim();
                        currentFields.Clear();
                    }

                    if (!string.IsNullOrWhiteSpace(fieldCell.Text))
                        currentFields.Add(fieldCell.Text.Trim());
                }

                if (currentMaterial != null && currentFields.Count > 0)
                    map[currentMaterial] = new List<string>(currentFields);
            }

            return map;
        }
    }
}
